//
//  MouthlyPlanHomePage.m
//  TimeManager2.0
//
//  Created by 刘凯敏 on 12/12/2016.
//  Copyright © 2016 刘凯敏. All rights reserved.
//

#import "MouthlyPlanHomePage.h"
#import "ColReusableView.h"
#import "DayColViewCell.h"

#define kSCREEN_WIDTH  [UIScreen mainScreen].bounds.size.width
#define kSCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

@interface MouthlyPlanHomePage () <UICollectionViewDelegate,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

//@property (nonatomic,strong) UICollectionView *collectionView;
@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;

@property (nonatomic,assign) NSInteger totalDayThisMonth;//本月总天数
@property (nonatomic,assign) NSInteger totalDayLastMonth;//上月总天数
@property (nonatomic,assign) NSInteger firstWeekDay;//本月第一天周几
@property (nonatomic,assign) NSInteger firstWeekDayNextMonth;//下月第一天周几
@property (nonatomic,assign) NSInteger lastSum;// =firstWeekDay，上个月格子数
@property (nonatomic,assign) NSInteger nextSum;//=7-firstWeekDayNM，下个月格子数
@property (nonatomic,assign) NSInteger sumDays;//=totalDayThisMonth+nextSum+lastSum，总格子数
//sumDays/7  总行数

@property (nonatomic,strong) NSDateComponents *comps;
@property (nonatomic,strong) NSCalendar *calendar;

@end

@implementation MouthlyPlanHomePage

//static NSString * const dayColID = @"dayColID";
//static NSString * const headerIdentifier = @"headerIdentifier";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    //使用[NSCalendar currentCalendar],iOS8以后会有bug,要加判断
    if ([NSCalendar respondsToSelector:@selector(calendarWithIdentifier:)]) {
        self.calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    } else {
        self.calendar = [NSCalendar currentCalendar];
    }
    //设置时区
    [self.calendar setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    
    self.comps =  [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:[NSDate date]];
    NSInteger thisMonth = [self.comps month];
    NSInteger thisYear = [self.comps year];
    //NSInteger thisDay = [self.comps day];
    
    NSLog(@"thisYear -- %ld,thisMonth -- %ld",(long)thisYear,(long)thisMonth);
    
    _totalDayThisMonth = [self getTotalDaysThisMonth:[NSDate date]];
    _totalDayLastMonth = [self getTotalDaysWithMonth:thisMonth - 1 withYear:thisYear];
    
    NSLog(@"_totalDayLastMonth -- %ld,_totalDayThisMonth -- %ld",_totalDayLastMonth,_totalDayThisMonth);
    
    _firstWeekDay = [self getWeekdayWithYear:thisYear month:thisMonth day:1];
    _firstWeekDayNextMonth = [self getWeekdayWithYear:thisYear month:thisMonth + 1 day:1];
    
    NSLog(@"_fisrtWeekDay -- %ld,_firstWeekDayNextMonth -- %ld",(long)_firstWeekDay,(long)_firstWeekDayNextMonth);
    
    if (_firstWeekDay == 7) {
        _lastSum = 0;
    }else{
        _lastSum = _firstWeekDay;
    }
    
    _nextSum = 7 - _firstWeekDayNextMonth;
    _sumDays = _totalDayThisMonth + _nextSum + _lastSum;
    //调用- (UICollectionView *)collectionView 方法
    [self collectionView];
}

#pragma mark - UICollectionViewDataSource

//第section有多少个格子
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _sumDays;
}

//表格实现
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    DayColViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"dayColID" forIndexPath:indexPath];
    
    //cell.backgroundColor = [UIColor colorWithRed:229 green:229 blue:229 alpha:0.5];
    cell.dayLabel.textColor = [UIColor groupTableViewBackgroundColor];
    
    //显示上个月日期
    if (indexPath.row < _lastSum) {
        //上月数据
        cell.dayLabel.text = [NSString stringWithFormat:@"%ld",(_totalDayLastMonth - _firstWeekDay + 1 + indexPath.row)];
        
    }else if(indexPath.row < _totalDayThisMonth + _lastSum){
        //本月数据展示
        cell.dayLabel.text = [NSString stringWithFormat:@"%ld",(indexPath.row + 1 - _lastSum)];
        cell.dayLabel.font = [UIFont boldSystemFontOfSize:14];
        //        cell.dayLabel.textColor = [UIColor colorWithRed:43 green:45 blue:49 alpha:0.5];
        cell.dayLabel.textColor = [UIColor blackColor];
        cell.backgroundColor = [UIColor whiteColor];
    }else{
        //下个月数据显示
        cell.dayLabel.text = [NSString stringWithFormat:@"%ld",(indexPath.row + 1 - _totalDayThisMonth - _lastSum)];
    }
    return cell;
}

//UICollectionView被选中时调用的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"didSelectItemAtIndexPath -- %ld",(long)indexPath.row);
}

//返回这个UICollectionView是否可以被选择
- (BOOL) collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

//表头实现
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        ColReusableView * headerCell = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerIdentifier" forIndexPath:indexPath];
        NSString *year = [NSString stringWithFormat:@"%ld",(long)[self.comps year]];
        NSString *month =[NSString stringWithFormat:@"%ld",(long)[self.comps month]];
        [headerCell updateTimer:@[year , month]];
        return headerCell;
    }
    return nil;
}

#pragma mark - 表格实现
//日历实现函数
- (UICollectionView *)collectionView{
    //if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        //日历长度
        float colW = kSCREEN_WIDTH - 30;
        //单元格长度和高度
        float cellW = colW/7;
        float cellH = cellW;
        //表头长度和高度
        float headerW = colW;
        float headerH = 50;
        
        [flowLayout setItemSize:CGSizeMake(cellW, cellH)];//设置cell的尺寸
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];//设置其布局方向
        [flowLayout setHeaderReferenceSize:CGSizeMake(headerW, headerH)];//设置表头长度和高度
        
        [flowLayout setMinimumInteritemSpacing:0];
        [flowLayout setMinimumLineSpacing:0];
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);//设置整个section的边界
        
        flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        
        CGFloat colH = (_sumDays / 7) * cellH + headerH + 3;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(15, 65, colW, colH) collectionViewLayout:flowLayout];
        //_collectionView.backgroundColor = [UIColor redColor];
        _collectionView.backgroundColor = [UIColor clearColor];
        
        [_collectionView registerNib:[DayColViewCell nib] forCellWithReuseIdentifier:@"dayColID"];
        [_collectionView registerNib:[UINib nibWithNibName:@"ColReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerIdentifier"];
        
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        
        _collectionView.layer.borderWidth = 3;
        _collectionView.layer.cornerRadius = 1;
        _collectionView.layer.borderColor = [UIColor colorWithRed:51 green:53 blue:58 alpha:1].CGColor;
        
        [self.view addSubview:_collectionView];
    //}
    return _collectionView;
}

#pragma mark - 获取当前月总天数NSInteger
- (NSInteger)getTotalDaysThisMonth:(NSDate *)date{
    NSRange range = [self.calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    return range.length;
}

#pragma mark - 判断给定月份的天数int
- (int)getTotalDaysWithMonth:(NSInteger)month withYear:(NSInteger)year{
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setMonth:month];
    [comps setYear:year];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian];
    NSDate *date = [gregorian dateFromComponents:comps];
    NSRange days = [gregorian rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    return (int)days.length;
}

#pragma mark - 判断给定日期是周几
//返回1--周一，7--周日
- (NSInteger)getWeekdayWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day {
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setDay:day];
    [comps setMonth:month];
    [comps setYear:year];
    
    
    NSDate *date = [self.calendar dateFromComponents:comps];
    NSLog(@"date -- %@",date);
    NSDateComponents *weekdayComponents = [self.calendar components:NSCalendarUnitWeekday fromDate:date];
    
    NSInteger weekDayNum = [weekdayComponents weekday] - 1;
    
    if (weekDayNum == 0) {
        weekDayNum = 7;
    }
    return weekDayNum;
}
@end
